import {
	defineStore
} from 'pinia'
import {
	ref
} from 'vue'

import {
	getInfo,
	login,
	logout,
	updatePwd
} from '@/api/user.js'
// 导入自定义的导航函数
import {
	navigateTo,
	toast
} from '@/utils/index.js';

const useUserStore = defineStore('user', () => {
	const userInfo = ref();

	const token = ref()

	const current = ref('Home');


	const userLogin = async (username, password) => {
		const res = await login(username, password)
		console.log("res-->", res)
		token.value = res.token

		if (!token.value) {
			return toast("登录失败", 'error')
		}

		const userRes = await getInfo()
		console.log("user-->", userRes)
		const {
			user
		} = userRes
		userInfo.value = user

		current.value = 'Home'; // 更新当前用户状态
		navigateTo('/pages/home/index'); // 导航到首页
	}

	const userLogout = () => {
		logout()
		token.value = undefined
		userInfo.value = undefined
		navigateTo('/pages/login/index');
	}


	const userUpdatePassword = async (oldPassword, newPassword) => {
		const res = await updatePwd(oldPassword, newPassword)
		console.log("修改密码res-->", res)
	}

	return {
		userInfo,
		current,
		token,
		userLogin,
		userLogout,
		userUpdatePassword
	}
}, {
	unistorage: true, // 开启后对 state 的数据读写都将持久化
})


export default useUserStore;